const News = require('../models/News')
const db = require('../db')
const _ = require('lodash')
const { debug } = require('../utils/constant')

//获取新闻列表
/* function NewsList() {
    return db.querySql(`select * from news order by id desc`)
} */
//获取对应分类的新闻列表
/* function NewsListCategory(id) {
    return db.querySql(`select * from news where columnid='${id}' order by id desc`)
} */
//获取新闻分类列表
/* function NewsCategoryList() {
    return db.querySql(`select * from category order by id desc`)
} */
async function NewsCategoryList() {
  const sql = 'select * from category order by id asc'
  const result = await db.querySql(sql)
  const categoryList = []
  result.forEach(item => {
    categoryList.push({
      label: item.categoryName,
      value: item.categoryName,
      num: item.id
    })
  })
  return categoryList
}
//获取单个新闻
function getOneNews(id) {
    return db.queryOne(`select * from news where id ='${id}' `)
}

//插入新闻
function insertNews(news) {
    return new Promise(async (resolve, reject) => {
        try {
            if (news) {
                await db.insert(news, 'news')//添加的表名
                resolve()

            } else {
                reject(new Error('添加的信息不正确'))
            }
        } catch (e) {
            reject(e)
        }
    })
}

//更新新闻
function updateNews(news) {
    return new Promise(async (resolve, reject) => {
        try {
            if (news) {
                await db.update(news, 'news' ,`where id='${news.id}'`)//添加的表名
                resolve()
            } else {
                reject(new Error('修改的信息不正确'))
            }
        } catch (e) {
            reject(e)
        }
    })
}

//删除新闻
function deleteNews(newsId) {
    return new Promise(async (resolve, reject) => {
        if(newsId){
            const sql = `delete from news where id='${newsId}'`
            db.querySql(sql).then(() => {
                resolve()
            })}
        else {
            reject(new Error('删除新闻信息失败'))
        }
    })
}

async function NewsList(query) {
    debug && console.log(query)
    const {
      columnid,
      title,
      sort,
      page = 1,
      pageSize = 20
    } = query
    const offset = (page - 1) * pageSize
    let newsSql = 'select * from news'
    let where = 'where'
    title && (where = db.andLike(where, 'title', title))
    columnid && (where = db.and(where, 'columnid', columnid))
    if (where !== 'where') {
      newsSql = `${newsSql} ${where}`
    }
    if (sort) {
      const symbol = sort[0]
      const column = sort.slice(1, sort.length)
      const order = symbol === '+' ? 'asc' : 'desc'
      newsSql = `${newsSql} order by \`${column}\` ${order}`
    }
    let countSql = `select count(*) as count from news`
    if (where !== 'where') {
      countSql = `${countSql} ${where}`
    }
    const count = await db.querySql(countSql)
    newsSql = `${newsSql} limit ${pageSize} offset ${offset}`
    const list = await db.querySql(newsSql)
    //list.forEach(news => news.cover = Book.genCoverUrl(book))
    return { list, count: count[0].count, page, pageSize }
  }
  
 /*  function deleteBook(fileName) {
    return new Promise(async (resolve, reject) => {
      let book = await getBook(fileName)
      if (book) {
        if (+book.updateType === 0) {
          reject(new Error('内置电子书不能删除'))
        } else {
          const bookObj = new Book(null, book)
          const sql = `delete from book where fileName='${fileName}'`
          db.querySql(sql).then(() => {
            bookObj.reset()
            resolve()
          })
        }
      } else {
        reject(new Error('电子书不存在'))
      }
    })
  } */

module.exports = {
    insertNews,
    updateNews,
    deleteNews,
    NewsList,
    NewsCategoryList,
    getOneNews
}
